package com.xywy.me.bean;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.xywy.R;
import com.xywy.common.constants.ResultCode;
import com.xywy.common.greendao.BaseDao;
import com.xywy.common.net.AsyncHttpClient;
import com.xywy.common.net.OnResultListenerAdapter;
import com.xywy.common.net.Parser;
import com.xywy.common.util.FileUtil;
import com.xywy.me.dao.UserDao;
import com.xywy.me.dao.UserDao.Properties;

import de.greenrobot.dao.query.Query;
import de.greenrobot.dao.query.QueryBuilder;

/**
 * 用来存储 当前登录用户信息的
 * @author wangwenlong
 *
 */
public class UserKeeper {
//     public static Jtcy currentUser;
//     public static Jtcy getCurrentUser(){
//    	 if(currentUser == null){
//    		 currentUser = new Jtcy();
//    		 currentUser.setAccountid(-1l);
//    	 }
//    	 return currentUser;
//     }
//     
//     public static void setCurrentUser(Jtcy user){
//    	 currentUser = user;
//     }
	
	public static User current_user;
	public static UserDao userDao;
	/**
	 * 登陆的当前用户
	 * @param context
	 * @return
	 */
	
	public static User getCurrentUser(Context context){
		if(userDao == null){
			userDao = BaseDao.getInstance(context).getUserDao();
		}
//		if(current_user == null){
			QueryBuilder<User> qb = userDao.queryBuilder();
			qb.where(Properties.Is_current.eq("true"));
			List<User> users = qb.list();
			if(users != null && users.size()>0){
				current_user = users.get(0);
				return current_user;
			}else {
				return null;
			}
//		}else {
//			return current_user;
//		}
	}
	
	/**
	 * 登陆过的用户列表
	 * @param context
	 * @return
	 */
	public static List<User> getLastLoginUser(Context context){
		if(userDao == null){
			userDao = BaseDao.getInstance(context).getUserDao();
		}
			QueryBuilder<User> qb = userDao.queryBuilder();
			qb.orderDesc(Properties.Last_login_time);
			List<User> users = qb.list();
			return users;
    }
	
	public static void saveUser(User user ,Context context){
		if(userDao == null){
			userDao = BaseDao.getInstance(context).getUserDao();
		}
		QueryBuilder<User> qb = userDao.queryBuilder().where(Properties.Userid.eq(user.getUserid()));
		List<User> list = qb.list();
		if(list != null && list.size()>0){
			//这个时候需要更新
			user.setId(list.get(0).getId());
			userDao.insertOrReplace(user);
		}else {
			//这个时候是插入
			userDao.insert(user);
		}
	}
	
	public static void logOut(User user){
		user.setIs_current(false);
		userDao.update(user);
	}
	
	static Parser paramsParser;
	static HashMap<String, Object> params;
	static AsyncHttpClient asyncHttpClient;
	public static void getUserAvatar(Context context,User user,Handler handler){
            System.out.println("sendMsg---------------------");
			// myProgress.start();
			paramsParser = new Parser();

			// 封装参数
			params = new HashMap<String, Object>();

			// 请求路径
			paramsParser.action = context.getString(R.string.get_account_data_list);
			// 请求方式
			paramsParser.request = "get";
			// 请求参数
			params.put("userid", user.getUserid());


			paramsParser.map = params;
			// 传递上下文
			paramsParser.context = context;

			asyncHttpClient = AsyncHttpClient.getInstance();
			asyncHttpClient.exeute(paramsParser, new AvatarResultAdapter(handler,user,context));
	}
	
	static class AvatarResultAdapter extends OnResultListenerAdapter{

         Handler handler;
         User user;
         Context context;
         public AvatarResultAdapter(Handler handler,User user,Context context){
        	 this.handler = handler;
        	 this.user = user;
         }
		@Override
		public <T extends Parser> void onSuccess(T resultParser, int resultCode) {
			super.onSuccess(resultParser, resultCode);
			System.out.println(resultParser.back);
			if(resultCode == ResultCode.SUCCESS){
				if(resultParser.back == null){
					handler.sendEmptyMessage(ResultCode.NULL);
					return;
				}else {
					try {
						JSONObject json = new JSONObject(resultParser.back);
						int state = json.optInt("state");
						if(state == ResultCode.SUCCESS){
							String avatar = json.optString("avatar");
							if(avatar != null && !avatar.endsWith(".jpg")){
								avatar +=".jpg";
							}
							user.setAvatar(avatar);
							user.setEmail(json.optString("email"));
							JSONArray jsonArray = json.optJSONArray("accounts");
						    
							if (null != jsonArray && jsonArray.length() > 0) {
								for (int i = 0; i < jsonArray.length(); i++) {
									JSONObject jsoninner = jsonArray.getJSONObject(i);
									if (jsoninner.optInt("accountid") == 0) {
										// mainAccout = cy;
										user.setAccountstr(jsoninner.optString("accountstr"));
									}
								}
								user.setIs_current(true);
								user.setLast_login_time(System.currentTimeMillis());
								saveUser(user, context);
							}
						
						}else {
							
						}
					} catch (Exception e) {
						e.printStackTrace();
						handler.sendEmptyMessage(ResultCode.NULL);
					}
					handler.sendEmptyMessage(ResultCode.SUCCESS);
				}
			}
		}

		public <T extends Parser> void onFailure(T parserResult, int resultCode) {
//			Message message = Message.obtain();
//			message.arg1 = resultCode;
//			message.obj = null;
			handler.sendEmptyMessage(ResultCode.FAIL);
		};

		public <T extends Parser> void onNoNetWork(T paramParser, int resultCode) {
//			Message message = Message.obtain();
//			message.arg1 = resultCode;
//			message.obj = null;
//			handler.sendMessage(message);
			handler.sendEmptyMessage(ResultCode.FAIL);
		};
	
	};
}
